//2006-03-20 by alex.kaplab@web.de
//using the intel TSC (Time Stamp Counter) register
//see also: http://www.linux-magazin.de/Service/Books/Buecher/HW-Treiber/flow.html

#ifndef timemeasure_h
#define timemeasure_h

#include <stdlib.h>
#include <string.h>

#include <asm/msr.h>

#ifdef __cplusplus
extern "C" {
#endif

u_int32_t tm_cpu_freq;
u_int32_t tm_ini_h, tm_ini_l, tm_end_h, tm_end_l;
u_int64_t tm_delta;
double    tm_secs;


int TM_INIT() //just get cpu frequency
{
    FILE *fp;
    int bufsize = 1024;
    char buf[bufsize];
    double freq;

    if(!(fp=fopen("/proc/cpuinfo","r"))) return -1;

    while(!feof(fp)) {
	fgets(buf,bufsize,fp);

	if(strstr(buf,"cpu MHz"))
	{
	    sscanf(buf,"cpu MHz : %lF",&freq);
	    tm_cpu_freq = (u_int32_t)(freq*1e6);
	    return 0;
	}
    }

    fclose(fp);
    return -1;
}

#define TM_START()  rdtsc(tm_ini_l,tm_ini_h)
#define TM_STOP() { rdtsc(tm_end_l,tm_end_h);\
                    tm_delta=( (((u_int64_t)tm_end_h)<<32 | tm_end_l)\
		              -(((u_int64_t)tm_ini_h)<<32 | tm_ini_l));\
                    tm_secs=((double)tm_delta) / tm_cpu_freq; }

#ifdef __cplusplus
}
#endif

#endif
